from typing import Any

from fastcrud import crud_router  # 异步ORM搭配异步CRUD路由
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession

from common import logger
from auth.security import get_password_hash
from dependencies.deps import get_db
from models.user import User  # 用户模型
from schemas.request.user import UserCreate, UserUpdate, UserSchema  # Pydantic 用户数据验证模型
from schemas.response import resp  # 统一的返回格式

router = crud_router(
    session=get_db,
    model=User,
    create_schema=UserCreate,
    update_schema=UserUpdate,
    path="/users",
    tags=["用户管理"]
)


# TODO: 覆盖写入创建用户的逻辑，用于hash密码存入数据库
@router.post("/users/create", summary="创建用户")
async def overwrite_create_user(
        *,
        db: AsyncSession = Depends(get_db),
        user_data: UserCreate
) -> Any:
    """
    创建用户
    """
    try:
        logger.info(f"Creating user: {user_data.username}")
        db_user = User(
            username=user_data.username,
            email=user_data.email,
            phone=user_data.phone,
            nickname=user_data.nickname,
            avatar=user_data.avatar,
            is_active=False,
            last_login=None,
            password=get_password_hash(user_data.password)
        )

        logger.info(f"Hashed password: {db_user.password}")
        db.add(db_user)
        await db.commit()
        await db.refresh(db_user)
        return resp.ok()
    except Exception as e:
        logger.error(f"Error creating user: {e}")
        await db.rollback()
        return resp.error(message="Failed to create user")


# @router.get("/", summary="获取所有用户")
# async def get_user_all(db: Session = Depends(get_db)) -> Any:
#     users = db.query(User).all()
#     return resp.ok(data=[user for user in users])
#
#
# @router.get("/{user_id}", summary="获取指定id用户")
# async def get_user_one(
#         user_id: int,
#         db: Session = Depends(get_db), ) -> Any:
#     user = db.query(User).filter(User.id == user_id).first()
#     if not user:
#         return resp.fail(resp.DataNotFound)
#     return resp.ok(data=user.dict())


# @router.put("/{user_id}", summary="更新用户")
# async def update_user(
#         user_id: int,
#         *,
#         db: Session = Depends(get_db),
#         user_data: User
# ) -> Any:
#     """
#     更新用户
#     """
#     user = db.query(User).filter(User.id == user_id).first()
#     if not user:
#         resp.fail(resp.DataNotFound)
#     db_user = jsonable_encoder(user_data, by_alias=True)
#     user.update(db_user)
#     db.commit()
#     return resp.ok(data=user)


# @router.delete("/{user_id}", summary="删除用户")
# async def delete_user(
#         user_id: int,
#         db: Session = Depends(get_db)
# ) -> Any:
#     """
#     删除用户
#     """
#     user = db.query(User).filter(User.id == user_id).first()
#     if not user:
#         resp.fail(resp.DataNotFound)
#     db.delete(user)
#     db.commit()
#     return resp.ok()
